<?php

require_once("include/bittorrent.php");
dbconn();
$id = (int) $_GET["id"];
if (!$id)
	httperr();
$passkey = $_GET['passkey'];
if ($passkey) {
	$res = sql_query("SELECT * FROM users WHERE passkey = " . sqlesc(mysql_real_escape_string($passkey)) . " LIMIT 1");
	$user = mysql_fetch_array($res);
	if (!$user)
		die("不存在的PassKey！");
	elseif ($user['enabled'] == 'no' || $user['parked'] == 'yes')
		die("帐号被封禁或被封存");
	$oldip = $user['ip'];
	$user['ip'] = getip();
	$CURUSER = $user;
}
else {
	loggedinorreturn();
	parked();
	$letdown = $_GET['letdown'];
	if (!$letdown && $CURUSER['showdlnotice'] == 1) {
		header("Location: " . get_protocol_prefix() . "$BASEURL/downloadnotice.php?torrentid=" . $id . "&type=firsttime");
	} elseif (!$letdown && $CURUSER['showclienterror'] == 'yes') {
		header("Location: " . get_protocol_prefix() . "$BASEURL/downloadnotice.php?torrentid=" . $id . "&type=client");
	} elseif (!$letdown && $CURUSER['leechwarn'] == 'yes') {
		header("Location: " . get_protocol_prefix() . "$BASEURL/downloadnotice.php?torrentid=" . $id . "&type=ratio");
	}
}
if ($CURUSER['seedbonus'] < -2000) {
	header("Location: " . get_protocol_prefix() . "$BASEURL/downloadnotice.php?torrentid=" . $id . "&type=bonus");
}
$res = sql_query("SELECT name, filename, save_as,  size, owner, banned, status, limitd, owner FROM torrents WHERE id = " . sqlesc($id)) or sqlerr(__FILE__, __LINE__);
$row = mysql_fetch_assoc($res);
//限定资源
if ($row['limitd'] == 'yes' && $row['owner'] != $CURUSER['id'] && get_user_class() < UC_MODERATOR) {
	stderr("啊哦", "该种子为限定资源，请先获得限定资源的下载资格。");
}
//强制分享
global $share, $sharesize, $sharenum, $sharemanage_class;
if ($share == "yes") {
	if ($CURUSER["id"] != $row['owner']) {
		$shareck = sql_query("SELECT size, status FROM torrents WHERE owner = " . $CURUSER['id']) or sqlerr(__FILE__, __LINE__);
		$userdonor = mysql_fetch_array(sql_query("SELECT donor FROM users WHERE id = " . $CURUSER['id'])) or sqlerr(__FILE__, __LINE__);
		if (get_user_class() >= $sharemanage_class || $userdonor['donor'] == 'yes') {
			$downhref = "download.php?id=" . $id . "&passkey=" . $CURUSER['passkey'];
		} else {
			$normalcount = 0;
			$sharecheck_sizesum = 0;
			while ($sharecheck = mysql_fetch_assoc($shareck)) {
				if ($sharecheck['status'] == 'normal') {
					$normalcount++;
					$sharecheck_sizesum += $sharecheck['size'];
				}
			}
			if ($normalcount >= $sharenum && $sharecheck_sizesum >= $sharesize) {
				$downhref = "download.php?id=" . $id . "&passkey=" . $CURUSER['passkey'];
			} else {
				header("Location: " . get_protocol_prefix() . "$BASEURL/downloadnotice.php?torrentid=" . $id . "&type=share");
			}
		}
	}
}
if ($iplog1 == "yes") {
	if (($oldip != $CURUSER["ip"]) && $CURUSER["ip"])
		sql_query("INSERT INTO iplog (ip, userid, access) VALUES (" . sqlesc($CURUSER['ip']) . ", " . $CURUSER['id'] . ", '" . $CURUSER['last_access'] . "')");
}
sql_query("UPDATE users SET last_access = " . sqlesc(date("Y-m-d H:i:s")) . ", ip = " . sqlesc($CURUSER['ip']) . "  WHERE id = " . sqlesc($CURUSER['id']));
if ($securetracker == 'yes' || $securetracker == 'op')
	$tracker_ssl = true;
elseif ($_COOKIE["c_secure_tracker_ssl"] == base64("yeah"))
	$tracker_ssl = true;
else
	$tracker_ssl = false;
if ($tracker_ssl == true) {
	$ssl_torrent = "https://";
	if ($https_announce_urls[0] != "")
		$base_announce_url = $https_announce_urls[0];
	else
		$base_announce_url = $announce_urls[0];
}
else {
	$ssl_torrent = "http://";
	$base_announce_url = $announce_urls[0];
}
$fn = "$torrent_dir/$id.torrent";
if ($CURUSER['downloadpos'] == "no")
	permissiondenied();
if (!$row || !is_file($fn) || !is_readable($fn))
	httperr();
//非发布者和普通用户不能下载被禁止(即回收站)和候选的种子
if (($row['banned'] == 'yes' || $row['status'] == 'candidate') && get_user_class() < $seebanned_class && $CURUSER["id"] != $row['owner'])
	permissiondenied();
//不符合禁区查看/下载要求不允许下载
$cat = getTorrentCat($id);
if ($cat >= '424') {
	if (get_user_class() < $freeviewlimit && $CURUSER['onlimit'] == 'no' && $CURUSER['id'] != $row['owner']) {
		stderr("错误", "您的权限不足以下载禁区内容，请在“控制台”->“安全设定”->“显示禁区”中勾选并付费开启。");
	}
}
sql_query("UPDATE torrents SET hits = hits + 1 WHERE id = " . sqlesc($id)) or sqlerr(__FILE__, __LINE__);

require_once("include/bencode.php");
$bencode = new BEncode();

if (strlen($CURUSER['passkey']) != 32) {
	$CURUSER['passkey'] = md5($CURUSER['username'] . date("Y-m-d H:i:s") . $CURUSER['passhash']);
	sql_query("UPDATE users SET passkey=" . sqlesc($CURUSER['passkey']) . " WHERE id=" . sqlesc($CURUSER['id']));
}

$dict = $bencode->bdecode_file($fn);
$dict['announce'] = $ssl_torrent . $base_announce_url . "?passkey=" . $CURUSER['passkey'] . "";

header("Content-Type: application/x-bittorrent");
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Transfer-Encoding: binary");

if (str_replace("Gecko", "", $_SERVER['HTTP_USER_AGENT']) != $_SERVER['HTTP_USER_AGENT']) {
	header("Content-Disposition: attachment; filename=\"$torrentnameprefix." . $row["save_as"] . ".torrent\" ; charset=utf-8");
} else if (str_replace("Firefox", "", $_SERVER['HTTP_USER_AGENT']) != $_SERVER['HTTP_USER_AGENT']) {
	header("Content-Disposition: attachment; filename=\"$torrentnameprefix." . $row["save_as"] . ".torrent\" ; charset=utf-8");
} else if (str_replace("Opera", "", $_SERVER['HTTP_USER_AGENT']) != $_SERVER['HTTP_USER_AGENT']) {
	header("Content-Disposition: attachment; filename=\"$torrentnameprefix." . $row["save_as"] . ".torrent\" ; charset=utf-8");
} else if (str_replace("IE", "", $_SERVER['HTTP_USER_AGENT']) != $_SERVER['HTTP_USER_AGENT']) {
	header("Content-Disposition: attachment; filename=" . str_replace("+", "%20", rawurlencode("$torrentnameprefix." . $row["save_as"] . ".torrent")));
} else {
	header("Content-Disposition: attachment; filename=" . str_replace("+", "%20", rawurlencode("$torrentnameprefix." . $row["save_as"] . ".torrent")));
}
print($bencode->bencode($dict));
